package cn.theten52.demo.patterns.design.behavior.memento.update1;

/**
 * TODO
 *
 * @author wangjin
 * @date 2021/4/4
 */
public class OriginatorImpl<T extends State> implements Originator<T> {
    ///发起者对象的状态    
    @SuppressWarnings("unchecked")
    protected T state = (T)(new StateImpl());
    //备忘录对象类型   
    private Class<?> clazz;

    @Override

    public Originator<T> setMementoType(Class<?> clazz) {
        this.clazz = clazz;
        return this;
    }

    /**
     * 获得备忘录
     */
    @SuppressWarnings("unchecked")
    @Override

    public Memento<T> get() throws InstantiationException, IllegalAccessException {
        if (clazz == null) {
            throw new NullPointerException();
        }
        return ((Memento<T>)(clazz.newInstance())).set((T)state.clone());
    }

    /**
     * 保存备忘录
     */
    @SuppressWarnings("unchecked")
    @Override

    public void set(Memento<T> memento) {
        if (memento == null) {
            throw new NullPointerException("memento");
        }
        this.state = (T)(memento.get().clone());
    }

    @Override

    public Originator<T> decrease() {
        state.decrease();
        return this;
    }

    @Override

    public Originator<T> increase() {
        state.increase();
        return this;
    }

    @Override

    public int current() {
        return state.value();
    }
}
 